package com.yinlei.appserver

import java.io.FileOutputStream
import java.io.PrintStream
import java.io.PrintWriter

/**
 * wifi传图
 * 1. 读取图片2进制数据并保存到文件
 * 2. 将图片路径回调到activity验证结果
 * 3，postman模拟http post请求
 */
open class UploadImageHandler : IResourceUriHandler {
    private var acceptPrefix = "/upload_image/"

    override fun accept(url: String) = url.startsWith(acceptPrefix)

    override fun handle(url: String, httpContext: HttpContext) {
//        val nos = httpContext.getUnderlySocket().getOutputStream()
//        with(PrintWriter(nos)) {
//            println("HTTP/1.1 200 OK")
//            println()
//            println("from upload image handler")
//            flush()
//        }
        val totalLength = httpContext.getRequestHeaderValue("Content-Length")!!.toLong()
        val temPath = "/mnt/sdcard/test/upload.jpg"
        val fos = FileOutputStream(temPath)
        val nis = httpContext.getUnderlySocket().getInputStream()
        val buffer = ByteArray(10240)
        var nReaded = 0
        var nLeftLength = totalLength // 剩余需要读取的字节
        while (nis.read(buffer).apply { nReaded = this } > 0 && nLeftLength > 0) {
            fos.write(buffer, 0, nReaded)
            nLeftLength -= nReaded
        }
        fos.close()

        val nos = httpContext.getUnderlySocket().getOutputStream()
        with(PrintStream(nos)) {
            println("HTTP/1.1 200 OK")
            println()
        }
        onImageLoaded(temPath)

    }

    open protected fun onImageLoaded(path: String) {

    }



}